package com.coldlz.mmp.common;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LogbackServiceProvider;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.classic.util.LogbackMDCAdapter;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.status.Status;
import ch.qos.logback.core.status.StatusListener;
import ch.qos.logback.core.status.StatusManager;
import ch.qos.logback.core.status.StatusUtil;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.ILoggerFactory;
import org.slf4j.IMarkerFactory;
import org.slf4j.helpers.BasicMarkerFactory;
import org.slf4j.helpers.Util;
import org.slf4j.spi.MDCAdapter;
import org.slf4j.spi.SLF4JServiceProvider;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 当前这个类和{@link LogbackServiceProvider}类大部分一样
 * 拷贝了一份这个源码，（目的是只打印 logback 初始化的错误日志，原本会打印很多无关紧要的日志）
 * 主要修改了方法{@link this#initializeLoggerContext()}
 */
public class SLF4JServiceProvider0 implements SLF4JServiceProvider {

    final static String NULL_CS_URL = CoreConstants.CODES_URL + "#null_CS";

    /**
     * Declare the version of the SLF4J API this implementation is compiled against.
     * The value of this field is modified with each major release.
     */
    // to avoid constant folding by the compiler, this field must *not* be final
    public static String REQUESTED_API_VERSION = LogbackServiceProvider.REQUESTED_API_VERSION; // !final

    private LoggerContext defaultLoggerContext;
    private IMarkerFactory markerFactory;
    private LogbackMDCAdapter mdcAdapter;
    // private final ContextSelectorStaticBinder contextSelectorBinder =
    // ContextSelectorStaticBinder.getSingleton();
//    private static Object KEY = new Object();
//    private volatile boolean initialized = false;

    @Override
    public void initialize() {
        defaultLoggerContext = new LoggerContext();
        // 替换掉默认的 StatusManager
        StatusManager statusManager = defaultLoggerContext.getStatusManager();
        defaultLoggerContext.setStatusManager(new StatusManager0(statusManager));

        defaultLoggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME);
        initializeLoggerContext();
        defaultLoggerContext.start();
        markerFactory = new BasicMarkerFactory();
        mdcAdapter = new LogbackMDCAdapter();
        // set the MDCAdapter for the defaultLoggerContext immediately
        defaultLoggerContext.setMDCAdapter(mdcAdapter);
    }

    private void initializeLoggerContext() {
        try {
            try {
                new ContextInitializer(defaultLoggerContext).autoConfig();
            } catch (JoranException je) {
                Util.report("Failed to auto configure default logger context", je);
            }
            // LOGBACK-292
            if (!StatusUtil.contextHasStatusListener(defaultLoggerContext)) {
                // 【修改的地方】
                StatusManager statusManager = defaultLoggerContext.getStatusManager();

                List<Status> copyOfStatusList = statusManager.getCopyOfStatusList();
                statusManager.clear();
                for (Status status : copyOfStatusList) {
                    if (status.getLevel() >= Status.ERROR) {
                        statusManager.add(status);
                    }
                }
                StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
            }
            // contextSelectorBinder.init(defaultLoggerContext, KEY);

        } catch (Exception t) { // see LOGBACK-1159
            Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t);
        }
    }

    @Override

    public ILoggerFactory getLoggerFactory() {
        return defaultLoggerContext;

//        if (!initialized) {
//            return defaultLoggerContext;
//
//
//        if (contextSelectorBinder.getContextSelector() == null) {
//            throw new IllegalStateException("contextSelector cannot be null. See also " + NULL_CS_URL);
//        }
//        return contextSelectorBinder.getContextSelector().getLoggerContext();
    }

    @Override
    public IMarkerFactory getMarkerFactory() {
        return markerFactory;
    }

    @Override
    public MDCAdapter getMDCAdapter() {
        return mdcAdapter;
    }

    @Override
    public String getRequestedApiVersion() {
        return REQUESTED_API_VERSION;
    }


    private static class StatusManager0 implements StatusManager{
        StatusManager statusManager;
        private StatusManager0(StatusManager statusManager){
            this.statusManager = statusManager;
        }

        @Override
        public void add(Status status) {
            statusManager.add(status);
        }

        @Override
        public List<Status> getCopyOfStatusList() {
            List<Status> copyOfStatusList = statusManager.getCopyOfStatusList();
            List<Status> result = new ArrayList<>(copyOfStatusList.size());
            for (Status status : copyOfStatusList) {
                if (status.getLevel() >= Status.WARN) {
                    result.add(status);
                }
            }
            return result;
        }

        @Override
        public int getCount() {
            return statusManager.getCount();
        }

        @Override
        public boolean add(StatusListener listener) {
            return statusManager.add(listener);
        }

        @Override
        public void remove(StatusListener listener) {
            statusManager.remove(listener);
        }

        @Override
        public void clear() {
            statusManager.clear();
        }

        @Override
        public List<StatusListener> getCopyOfStatusListenerList() {
            return statusManager.getCopyOfStatusListenerList();
        }
    }
}
